import SingleBase from '../../base/SingleBase';
import PlatformApi from '../PlatformApi';
import { event_base } from '../../../config/ClientEvent';
export interface videoAdType {
    show();

    onLoad();

    offLoad();

    load();

    onError(errorHandler: Function);

    offError();

    onClose(callback: Function);

    offClose(callback: Function);
}

export default class TtApi extends SingleBase implements PlatformApi {
    videoAd: videoAdType;
    enabled: boolean = false;
    videoPath: string;
    callback: Function;
    recorder: any;
    appName: string;
    InterstitialAd: any = undefined;

    onLoad() {
        this.showShareMenu();
        let self = this;
        tt.getSystemInfo({
            success(res) {
                self.appName = res.appName;
                self.enabled = true;
                self.loadVideoAd();
                if (self.appName !== 'devtools') {
                    self.loadRecordVideo(res);
                }
            },
            fail(res) {
                console.log(`getSystemInfo 调用失败`);
            },
        });
    }

    setFrameRate(fps: number) {
        tt.setPreferredFramesPerSecond(fps);
    }

    /*关注*/
    openAwemeUserProfile(callback: Function) {
        if (this.appName !== 'Douyin') {
            this.showToast('请在抖音中关注');
            return;
        }
        let date = Date.now();
        let self = this;

        function onShowCallback(res) {
            tt.offShow(onShowCallback);
            let t = Date.now() - date;
            if (t >= 3000) {
                if (callback) {
                    callback();
                }
            } else {
                self.showToast('关注失败', 'fail');
            }
        }

        tt.offShow(onShowCallback);
        tt.onShow(onShowCallback);
        tt.openAwemeUserProfile();
    }

    isPlatform(): boolean {
        return !!window.tt;
    }

    isRecordVideo(): boolean {
        return !!this.videoPath;
    }

    showToast(title: string, icon: string = 'none', duration: number = 2000) {
        tt.showToast({ title, duration, icon });
    }

    startRecordVideo(duration: number = 200) {
        if (!this.recorder) {
            return;
        }
        this.recorder.start({
            duration: duration,
            isMarkOpen: false,
        });
    }

    _stopRecordVideo: Function;
    stopRecordVideo(cb?: Function) {
        if (!this.recorder) {
            return;
        }
        this._stopRecordVideo = cb;;
        this.recorder.stop();
    }

    loadRecordVideo(res) {
        this.recorder = tt.getGameRecorderManager();
        const screenWidth = res.screenWidth;
        const screenHeight = res.screenHeight;
        const recorder = tt.getGameRecorderManager();
        const maskInfo = recorder.getMark();
        const x = (screenWidth - maskInfo.markWidth) / 2;
        const y = (screenHeight - maskInfo.markHeight) / 2;
        this.recorder.onStart((res) => {
            console.log("录屏开始");
            // do something;
        });
        this.recorder.onStop((res) => {
            this.videoPath = res.videoPath;
            console.log('录屏结束', res);
            if(this._stopRecordVideo)this.startRecordVideo();
        });
        this.recorder.onPause(res => {
            console.log(res)
        });
        this.recorder.onResume(res => {
            console.log(res)
        });
        this.recorder.onError(res => {
            console.log(res)
        });
    }

    loadVideoAd() {
        this.videoAd = tt.createRewardedVideoAd({
            adUnitId: '27jtro8owmbanj9ea2',
        });

        this.videoAd.onClose((res) => {
            if (res.isEnded) {
                if (this.callback) {
                    this.callback();
                }
            } else {
                this.showToast('需要完整播放视频才能领取奖励哟！', 'none')
            }
            this.callback = null;
            this.videoAd.load()
                .then(() => {
                    console.log('reloaded next video');
                })
                .catch(err => {
                    console.error('reload next video fail');
                });
        });

        this.videoAd.onError((err) => {
            console.log('onError' + err);
            // this.showToast('视频加载错误', 'fail');
        });
    }

    showVideoAd(callback: Function, is_share: boolean = true) {
        if (!this.enabled) {
            this.showToast('当前版本无法显示视频', 'none');
            return;
        }
        this.callback = callback;
        this.videoAd.show()
            .then(() => {
                console.log('video success');
            })
            .catch(err => {
                console.error('video fail');
                this.reLoadVideo();
            })
    }

    reLoadVideo() {
        this.videoAd.load().then(() => {
            this.videoAd.show();
            console.log('video success');
        })
            .catch(err => {
                this.showToast('视频显示失败, 稍后重试', 'fail');
                console.error('video fail');
            });
    }


    showShareMenu() {
        tt.showShareMenu({
            templateId: "1cc3n7odhi9j6c0000", // 替换成通过审核的分享ID
            title: "超速战机",
            desc: "简单的几何，不简单的游戏",
            imageUrl: ".share.jpg",
            success(res) {
                console.log("已成功显示转发按钮");
            },
            fail(err) {
                console.log("showShareMenu 调用失败", err.errMsg);
            },
            complete(res) {
                console.log("showShareMenu 调用完成");
            },
        });
    }

    onShareAppMessage(callback: Function, is_reward: boolean = true) {
        let self = this;
        tt.shareAppMessage({
            templateId: "1cc3n7odhi9j6c0000", // 替换成通过审核的分享ID
            title: "超速战机",
            desc: "简单的几何，不简单的游戏",
            imageUrl: ".share.jpg",
            query: "",
            success() {
                console.log("分享视频成功");
                self.showToast('分享成功');
                callback && callback();
            },
            fail(e) {
                if (is_reward) {
                    self.showToast('需要分享游戏给好友才能获得奖励哟！');
                }
            },
        });
    }

    /*
        视频分享
    * */
    onShareAppVideo(callback: Function, is_reward: boolean = false) {
        let videoPath = this.videoPath;
        if (!videoPath) {
            this.onShareAppMessage(callback, is_reward);
            return;
        }

        let self = this;
        tt.shareAppMessage({
            channel: "video",
            title: "超速战机",
            desc: "简单的几何，不简单的游戏",
            imageUrl: "分享图片url",
            templateId: "1cc3n7odhi9j6c0000", // 替换成通过审核的分享ID
            query: "",
            extra: {
                videoPath: videoPath, // 可替换成录屏得到的视频地址
                videoTopics: ["超速战机", "抖音小游戏", "解压小游戏"], //该字段已经被hashtag_list代替，为保证兼容性，建议两个都填写。
                hashtag_list: ["超速战机", "抖音小游戏", "解压小游戏"],
                video_title: "简单的几何，不简单的游戏", //生成的默认内容
            },
            success() {
                console.log("分享视频成功");
                self.showToast('分享视频成功');
                callback();
            },
            fail(e) {
                if (is_reward) {
                    self.showToast('需要分享录屏才能领取奖励有！');
                }
            },
        });
    }

    reportAnalytics(name: string, data: any = {}): void {
        tt.reportAnalytics(name, data);
    }

    createInterstitialAd() {
        return
        try {
            console.log("加载插屏广告")
            this.InterstitialAd = tt.createInterstitialAd({
                adUnitId: '5ncaoc99one891428i',
            });
            this.InterstitialAd.onLoad(() => {//创建会自动load
                this.InterstitialAd.show().then(() => {
                    console.log("插屏广告展示成功");
                });
            })
            // 自动load 的失败会走到这里
            this.InterstitialAd.onError(() => {
                this.InterstitialAd.destroy();
            });
        } catch (error) {

        }
    }

    showInterstitialAd() {
        this.createInterstitialAd();
    }
}